#include "UdpClient.hpp"
#include "Comm.hpp"
#include <iostream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <cstdlib>
#include <string>
#include <pthread.h>
#include <signal.h>

int sockfd = -1;
struct sockaddr_in server;

void ClientQuit(int signo)
{
    (void)signo;
    const std::string quit = "QUIT";
    int n = ::sendto(sockfd,quit.c_str(),quit.size(),0,CONV(&server),sizeof(server));
    exit(0);
}

void* Recver(void *args)
{
    while(true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int n = ::recvfrom(sockfd,buffer,sizeof(buffer) - 1,0,CONV(&temp),&len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer <<std::endl;
        }
    }
}

// ./client_udp serverip serverport----客户端需r要先知道服务器的端口号和IP
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage" << argv[0] << "serverip serverport" << std::endl;
        Die(USAGE_ERR);
    }
    signal(2,ClientQuit);
    std::string serverip = argv[1];
    // 命令行上输入的都是字符串
    uint16_t serverport = std::stoi(argv[2]);

    // 1. 创建套接字
    sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        Die(SOCKET_ERR);
    }

    // 1.1 填充server信息
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    // 需要调用主机转网络
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());

    pthread_t thread;
    pthread_create(&thread,nullptr,Recver,nullptr);
    // 2. clientdone
    while (true)
    {
        std::cout << "please Entrer: ";
        std::string message;
        std::getline(std::cin, message);
        //这里只有发消息才能收到消息，回车收消息
        int n = ::sendto(sockfd, message.c_str(), message.size(), 0, CONV(&server), sizeof(server));
        (void)n;
    }
    return 0;
}
